<template>
  <div class="calculation-config-step">
    <div class="calculation-config-container">
      <div class="main-content">
        <div class="config-sections">
          <!-- 输入通道模块 -->
          <!-- <div class="section-card">
            <div class="section-title">输入通道</div>
            <div class="section-content">
              <div class="form-row">
                <label>通道选择</label>
                <select v-model="formState.inputChannel">
                  <option v-for="ch in ['AI1', 'AI2', 'AI3']" :key="ch" :value="ch">{{ ch }}</option>
                </select>
              </div>
            </div>
          </div> -->

          <!-- 计算类型模块 -->
          <div class="section-card">
            <div class="section-title">计算类型</div>
            <div class="section-content">
              <div class="form-row">
                <label>参数集一</label>
                <select v-model="formState.calcType1" @change="handleCalcTypeChange">
                  <option v-for="option in CALC_TYPE1_OPTIONS" :key="option.value" :value="option.value">
                    {{ option.label }}
                  </option>
                </select>
              </div>

              <div class="form-row">
                <label>参数集二</label>
                <select v-model="formState.calcType2" @change="handleCalcTypeChange">
                  <option v-for="option in CALC_TYPE2_OPTIONS" :key="option.value" :value="option.value">
                    {{ option.label }}
                  </option>
                </select>
              </div>

              <!-- 动态参数区域 -->
              <div v-if="formState.calcType1 && formState.calcType2">
                <!-- 基于块 -->
                <template v-if="formState.calcType1 === 'block'">
                  <div class="form-row">
                    <label>块大小</label>
                    <select v-model="formState.blockSize">
                      <option v-for="size in BLOCK_SIZE_OPTIONS" :key="size" :value="size">
                        {{ size }}
                      </option>
                    </select>
                  </div>
                  <div class="form-row">
                    <label>重叠定义</label>
                    <select v-model="formState.overlapType" @change="handleOverlapTypeChange">
                      <!-- <option value="percent">百分比形式</option> -->
                      <option value="absolute">绝对值形式</option>
                    </select>
                  </div>
                  <div class="form-row">
                    <label>{{ formState.overlapType === 'percent' ? '重叠百分比' : '重叠值' }}</label>
                    <select v-if="formState.overlapType === 'percent'" v-model="formState.overlapValue">
                      <option v-for="val in [0, 50, 66, 75]" :key="val" :value="val">
                        {{ val }}%
                      </option>
                    </select>
                    <input v-else type="number" v-model="formState.overlapValue" :min="0" :step="0.1" />
                  </div>
                </template>

                <!-- 连续的 -->
                <template v-else-if="formState.calcType1 === 'continuous'">
                  <div class="form-row">
                    <label>块大小</label>
                    <select v-model="formState.blockSize">
                      <option v-for="size in BLOCK_SIZE_OPTIONS" :key="size" :value="size">
                        {{ size }}
                      </option>
                    </select>
                  </div>
                </template>

                <!-- 触发类型 -->
                <template v-if="formState.calcType1.includes('Trigger')">
                  <div class="form-row">
                    <input type="checkbox" v-model="formState.perSample" id="perSample" />
                    <label for="perSample">基于每个采样点</label>
                  </div>

                  <!-- 单条件触发 -->
                  <template v-if="formState.calcType1 === 'singleTrigger'">
                    <div class="form-row">
                      <label>触发通道</label>
                      <select v-model="formState.triggerChannel">
                        <option v-for="ch in ['AI1', 'AI2', 'AI3']" :key="ch" :value="ch">
                          {{ ch }}
                        </option>
                      </select>
                    </div>
                    <template v-if="!formState.perSample">
                      <div class="form-row">
                        <label>模式</label>
                        <select v-model="formState.triggerMode">
                          <option v-for="mode in TRIGGER_MODES" :key="mode" :value="mode">
                            {{ mode }}
                          </option>
                        </select>
                      </div>
                      <div class="form-row">
                        <label>方向</label>
                        <select v-model="formState.triggerDirection">
                          <option value="positive">正向</option>
                          <option value="negative">负向</option>
                        </select>
                      </div>
                      <div class="form-row">
                        <label>触发值(V)</label>
                        <input type="number" v-model="formState.triggerValue" :min="0" :step="0.1" />
                      </div>
                    </template>
                  </template>

                  <!-- 双条件触发 -->
                  <template v-else-if="formState.calcType1 === 'doubleTrigger'">
                    <div class="section-subtitle">开始触发条件</div>
                    <div class="form-row">
                      <label>触发通道</label>
                      <select v-model="formState.startTriggerChannel">
                        <option v-for="ch in ['AI1', 'AI2', 'AI3']" :key="ch" :value="ch">
                          {{ ch }}
                        </option>
                      </select>
                    </div>
                    <template v-if="!formState.perSample">
                      <div class="form-row">
                        <label>模式</label>
                        <select v-model="formState.startTriggerMode">
                          <option v-for="mode in TRIGGER_MODES" :key="mode" :value="mode">
                            {{ mode }}
                          </option>
                        </select>
                      </div>
                      <div class="form-row">
                        <label>方向</label>
                        <select v-model="formState.startTriggerDirection">
                          <option value="positive">正向</option>
                          <option value="negative">负向</option>
                        </select>
                      </div>
                      <div class="form-row">
                        <label>触发值(V)</label>
                        <input type="number" v-model="formState.startTriggerValue" :min="0" :step="0.1" />
                      </div>
                    </template>

                    <div class="section-subtitle">停止触发条件</div>
                    <div class="form-row">
                      <label>触发通道</label>
                      <select v-model="formState.stopTriggerChannel">
                        <option v-for="ch in ['AI1', 'AI2', 'AI3']" :key="ch" :value="ch">
                          {{ ch }}
                        </option>
                      </select>
                    </div>
                    <template v-if="!formState.perSample">
                      <div class="form-row">
                        <label>模式</label>
                        <select v-model="formState.stopTriggerMode">
                          <option v-for="mode in TRIGGER_MODES" :key="mode" :value="mode">
                            {{ mode }}
                          </option>
                        </select>
                      </div>
                      <div class="form-row">
                        <label>方向</label>
                        <select v-model="formState.stopTriggerDirection">
                          <option value="positive">正向</option>
                          <option value="negative">负向</option>
                        </select>
                      </div>
                      <div class="form-row">
                        <label>触发值(V)</label>
                        <input type="number" v-model="formState.stopTriggerValue" :min="0" :step="0.1" />
                      </div>
                    </template>
                  </template>
                </template>
              </div>
            </div>
          </div>

          <!-- 输出通道模块 -->
          <div class="section-card">
            <div class="section-title">输出通道参数</div>
            <div class="section-content">
              <div class="checkbox-group">
                <div v-for="option in filteredOutputOptions" :key="option.value" class="checkbox-item">
                  <input type="checkbox" :id="option.value" :value="option.value" v-model="formState.outputParams" />
                  <label :for="option.value">{{ option.label }}</label>
                </div>
              </div>
            </div>
          </div>

          <!-- 输出模块 -->
          <!-- <div class="section-card">
            <div class="section-title">输出配置</div>
            <div class="section-content">
              <div class="form-row">
                <label>名称</label>
                <input type="text" v-model="formState.outputName" />
              </div>
              <div class="form-row">
                <label>描述</label>
                <input type="text" v-model="formState.outputDesc" />
              </div>
              <div class="form-row">
                <label>单位</label>
                <input type="text" v-model="formState.outputUnit" />
              </div>
              <div class="form-row">
                <label>颜色</label>
                <input type="color" v-model="formState.outputColor" class="color-picker" />
              </div>
            </div>
          </div> -->
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed, onMounted } from 'vue'
import type { CalculationConfig, FilterConfig } from '@/apis/task/dataAnalysis'
import {
  CALC_TYPE1_OPTIONS,
  CALC_TYPE2_OPTIONS,
  TRIGGER_MODES,
  BLOCK_SIZE_OPTIONS,
  OUTPUT_OPTIONS
} from '@/apis/task/dataAnalysis'

const props = defineProps({
  initialData: {
    type: Object as () => CalculationConfig | null,
    default: null
  },
  filterConfig: {
    type: Object as () => FilterConfig | null,
    default: null
  }
})

const emit = defineEmits(['valid'])

// 表单状态
const formState = reactive<CalculationConfig>({
  inputChannel: 'AI1',
  calcType1: 'block',
  calcType2: 'time',
  blockSize: 0.1,
  overlapType: 'absolute',
  overlapValue: 0.0,
  perSample: false,
  triggerChannel: '',
  triggerMode: '',
  triggerDirection: 'positive',
  triggerValue: 0,
  startTriggerChannel: '',
  startTriggerMode: '',
  startTriggerDirection: 'positive',
  startTriggerValue: 0,
  stopTriggerChannel: '',
  stopTriggerMode: '',
  stopTriggerDirection: 'positive',
  stopTriggerValue: 0,
  outputParams: [],
  outputName: '',
  outputDesc: '',
  outputUnit: '',
  outputColor: '#1890ff'
})

// 根据计算类型过滤输出参数选项
const filteredOutputOptions = computed(() => {
  if (!formState.calcType1 || !formState.calcType2) return []

  // 公共基础参数
  const baseParams = [
    'RMS', 'rms2', 'acrms', 'variance', 'mean',
    'stdDev', 'marginFactor', 'cumulative', 'coeffVariation'
  ]

  // 基于块
  if (formState.calcType1 === 'block') {
    return OUTPUT_OPTIONS.filter(opt =>
      baseParams.includes(opt.value) ||
      [
        'min', 'minTime', 'max', 'maxTime', 'kurtosis',
        'peak', 'skewness', 'peakToPeak', 'crestFactor'
      ].includes(opt.value)
    )
  }

  // 连续的
  if (formState.calcType1 === 'continuous') {
    return OUTPUT_OPTIONS.filter(opt =>
      baseParams.includes(opt.value) ||
      ['median', 'kurtosis', 'skewness'].includes(opt.value))
  }

  // 单一值
  if (formState.calcType1 === 'singleValue') {
    return OUTPUT_OPTIONS.filter(opt =>
      baseParams.includes(opt.value) ||
      [
        'min', 'minTime', 'max', 'maxTime', 'kurtosis',
        'peak', 'skewness', 'peakToPeak', 'crestFactor'
      ].includes(opt.value))
  }

  // 触发类型
  if (formState.calcType1.includes('Trigger')) {
    return OUTPUT_OPTIONS.filter(opt =>
      baseParams.includes(opt.value) ||
      [
        'min', 'minTime', 'max', 'maxTime', 'kurtosis',
        'peak', 'skewness', 'peakToPeak', 'crestFactor'
      ].includes(opt.value))
  }

  return []
})

// 处理计算类型变化
const handleCalcTypeChange = () => {
  formState.outputParams = []
  validateForm()
}

// 处理重叠类型变化
const handleOverlapTypeChange = () => {
  formState.overlapValue = formState.overlapType === 'percent' ? 0 : 0.1
}

// 验证表单
const validateForm = () => {
  const isValid = !!formState.calcType1 &&
    !!formState.calcType2 &&
    formState.outputParams.length > 0 &&
    !!formState.outputName
  emit('valid', isValid)
  return isValid
}

// 获取配置
const getConfig = () => {
  // return validateForm() ? {...formState} : null
  return { ...formState }
}

// 初始化表单
const initForm = () => {
  if (props.initialData) {
    Object.assign(formState, props.initialData)
  }
  validateForm()
}

// 监听表单变化
watch(formState, () => {
  validateForm()
}, { deep: true })

onMounted(() => {
  initForm()
})

defineExpose({
  getConfig
})
</script>

<style scoped>
/* 复用原来的样式，但移除弹窗相关样式 */
.calculation-config-step {
  height: 100%;
}

.calculation-config-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  border: 1px solid #ccc;
  background-color: #f0f0f0;
  font-family: Arial, sans-serif;
}

.main-content {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.config-sections {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.section-card {
  border: 1px solid #ccc;
  background-color: white;
  margin-bottom: 10px;
}

.section-title {
  background-color: #e0e0e0;
  padding: 5px 10px;
  font-weight: bold;
  border-bottom: 1px solid #ccc;
}

.section-subtitle {
  font-weight: bold;
  margin: 10px 0 5px;
  padding-left: 10px;
}

.section-content {
  padding: 10px;
}

.form-row {
  display: flex;
  align-items: center;
  margin: 10px 0;
  gap: 10px;
}

.form-row label {
  width: 100px;
  text-align: right;
}

select,
input[type="text"],
input[type="number"] {
  flex: 1;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 3px;
}

.checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.checkbox-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.color-picker {
  width: 40px;
  height: 40px;
  border: none;
  cursor: pointer;
}

@media (max-width: 992px) {
  .config-sections {
    grid-template-columns: 1fr;
  }
}
</style>